// 函数对象
window.funObj = {};
// 日历数据存这里
window.calData = {
    "interval": null
};
// 日历对象存这里
window.calContentObj = {};
// 日历常量
window.calConstant = {
    "url": {
        "event": {
            "getByMonth": "/calendar/event/getByMonth",
            "saveEvent": "/calendar/event/saveEvent",
            "deleteEvent": "/calendar/event/deleteEvent",
            "updateStatus": "/calendar/event/updateStatus"
        },
        "config": {
            "getInterval": "/calendar/config/getInterval",
            "saveInterval": "/calendar/config/saveInterval"
        }
    },
    'color': {
        // 'study': '#FFB5B5',
        'study': '#E9967A',
        'review': '#8CC7B5',
        'finished': '#cbced2'
    },
};

// 获取今天时间 isInt true:yyyyMM , false: yyyy-MM-dd
funObj.getToday = function (isInt) {
    var date = new Date();
    var nowMonth = date.getMonth() + 1;
    var strDate = date.getDate();
    var seperator = "-";
    if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (isInt) {
        return date.getFullYear() + nowMonth;
    } else {
        return date.getFullYear() + seperator + nowMonth + seperator + strDate;
    }
};

// 转换时间格式  yyyyMMdd
funObj.convertDate = function (day, containsDate) {
    let yearAndMonth = day.year() + '' + (day.month() >= 9 ? (day.month() + 1) : '0' + (day.month() + 1));
    if (containsDate) {
        return yearAndMonth + '' + (day.date() >= 10 ? day.date() : '0' + day.date());
    } else {
        return yearAndMonth;
    }
};

// 比较是否拖拽落在垃圾桶上
funObj.isEventOverDiv = function (x, y) {
    // debugger
    let external_events = $('#external-events');
    let offset = external_events.offset();
    // debugger
    console.log("x:" + x + ",y:" + y);
    console.dir(offset);
    offset.right = external_events.width() + offset.left;
    offset.bottom = external_events.height() + offset.top;

    console.log(offset.right);
    console.log(offset.bottom);

    return (x >= offset.left
        && y >= offset.top
        && x <= offset.right
        && y <= offset.bottom);
};

// 从数据库加载events
funObj.loadEvents = function (start, end, timezone, callback) {
    // 拼接字符串
    if (start && end) {
        start = funObj.convertDate(start, false);
        end = funObj.convertDate(end, false);
    } else {
        start = funObj.getToday(1);
        end = funObj.getToday(1);
    }

    $.ajax({
        url: calConstant.url.event.getByMonth,
        data: {"start": start, "end": end},
        type: "GET",
        dataType: "json",
        success: function (result) {
            var resultEvents = [];
            if (result.data) {
                for (let i = 0; i < result.data.length; i++) {
                    let tempEvent = {};
                    let isOriginal = result.data[i].isOriginal;
                    tempEvent.eventId = result.data[i].eventId;
                    tempEvent.planId = result.data[i].planId;
                    tempEvent.status = result.data[i].status;
                    tempEvent.isOriginal = isOriginal;
                    tempEvent.start = result.data[i].day;
                    tempEvent.title = result.data[i].title;
                    tempEvent.color = isOriginal ? calConstant.color.study : calConstant.color.review;
                    tempEvent.className = isOriginal ? 'study' : 'review';

                    // 状态已完成且是复习，置为灰色
                    if (tempEvent.status === 1 && !isOriginal) {
                        tempEvent.color = calConstant.color.finished;
                    }
                    resultEvents[resultEvents.length] = tempEvent;
                }
            }
            callback(resultEvents);
        }
    });
};

// 点击保存事件
funObj.saveEvents = function (start, end) {
    var title = prompt('今天要学点什么呢：');
    let eventData;
    if (title) {
        eventData = {
            title: title,
            day: funObj.convertDate(start, 1),
            color: ""
        };
        $.ajax({
            url: calConstant.url.event.saveEvent,
            data: JSON.stringify(eventData),
            type: "POST",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (result) {
                $('#calendar').fullCalendar('refetchEvents')
            }
        });
    }
};

// 点击修改间隔
funObj.saveInterval = async function () {
    if (!calData.interval) {
        // 查询
        await funObj.getInterval();
    }

    let title = '当前复习间隔天数:' + calData.interval + ", 请修改新的复习间隔天数（逗号隔开,例如:1,3,4）";
    let value = prompt(title);
    if (value) {
        $.ajax({
            url: calConstant.url.config.saveInterval,
            data: {"value": value},
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType: "json",
            success: function (result) {
                $('#calendar').fullCalendar('refetchEvents')

                alert("修改成功");
            }
        });
        calData.interval = null;
    }
};

// 查询间隔
funObj.getInterval = function () {
    $.ajax({
        async: false,   //同步
        url: calConstant.url.config.getInterval,
        type: "GET",
        dataType: "json",
        success: function (result) {
            calData.interval = result.data;
        }
    });
};

// 删除事件
funObj.deleteEvents = function (calEvent) {
    let eventData = {
        "eventId": calEvent.eventId,
        "planId": calEvent.planId,
        "isOriginal": calEvent.isOriginal
    };
    $.ajax({
        url: calConstant.url.event.deleteEvent,
        data: JSON.stringify(eventData),
        type: "POST",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function (result) {
            $('#calendar').fullCalendar('refetchEvents')
        }
    });
};

// 更改事件状态
funObj.changeStatus = function (calEvent, jsEvent, view) {
    let eventData = {
        "eventId": calEvent.eventId,
        "status": calEvent.status
    };
    $.ajax({
        url: calConstant.url.event.updateStatus,
        data: JSON.stringify(eventData),
        type: "POST",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function (result) {
            $('#calendar').fullCalendar('refetchEvents')
        }
    });
};

//  初始化
funObj.init = function () {
    calContentObj = {
        // themeSystem: 'jquery-ui',
        header: {
            left: 'prevYear,prev,next,nextYear today',
            center: 'title',
            right: 'myCustomButton'
        },
        timeZone: 'Asia/Shanghai',
        defaultDate: funObj.getToday(0),
        navLinks: false, // can click day/week names to navigate views
        selectable: true,
        selectHelper: true,
        dayClick: funObj.saveEvents,
        editable: true,
        eventClick: funObj.changeStatus,
        eventLimit: true, // allow "more" link when too many events
        events: funObj.loadEvents,
        eventStartEditable: true,    // 不让拖拽
        eventDurationEditable: false,
        dragOpacity: 0.2,    // 拖拽时的透明度，浮点型，默认0.75。取值范围0.0～1.0
        dragRevertDuration: 200, //当拖动事件失败后，恢复到原来的位置所需时间，默认500ms。
        eventMouseover: funObj.eventMouseover, // 鼠标移入
        eventMouseout: funObj.eventMouseout, // 鼠标移出
        customButtons: {
            myCustomButton: {
                text: '修改复习间隔',
                click: funObj.saveInterval
            }
        },
        // 回调函数，当事件拖动停止后触发
        eventDragStop: function (event, jsEvent) {
            if (funObj.isEventOverDiv(jsEvent.clientX, jsEvent.clientY)) {
                funObj.deleteEvents(event);
            }
        },
        // 回调函数，当拖动结束且日程移动另一个时间时触发，回滚，不改变事件时间
        eventDrop: function (event, delta, revertFunc) {
            revertFunc();
        },
    };
    $('#calendar').fullCalendar(calContentObj);
};

$(function () {
    funObj.init();
    $('[data-toggle="popover"]').popover();
});

